package com.situ.crm2026.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.crm2026.dao.CourseMapper;
import com.situ.crm2026.dao.MemberCourseReservationMapper;
import com.situ.crm2026.model.Course;
import com.situ.crm2026.model.MemberCourseReservation;
import com.situ.crm2026.model.dto.ReservationDto;
import com.situ.crm2026.service.CourseService;
import com.situ.crm2026.service.MemberCourseReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MemberCourseReservationServiceImpl implements MemberCourseReservationService {

    private MemberCourseReservationMapper reservationMapper;
    private CourseMapper courseMapper;

    @Autowired
    public void setReservationMapper(MemberCourseReservationMapper reservationMapper) {
        this.reservationMapper = reservationMapper;
    }

    private CourseService courseService;

    @Autowired
    public void setCourseService(CourseService courseService) {
        this.courseService = courseService;
    }

    // 保存预约
    @Override
    @Transactional
    @CacheEvict(value = "com.situ.crm2026.impl.courseServiceImpl", allEntries = true)
    public boolean reserve(Integer memberId, Integer courseId, Integer status,Integer courseType) {
        // 检查是否已预约（包括任何状态的预约）
        if (reservationMapper.selectOne(
                new LambdaQueryWrapper<MemberCourseReservation>()
                        .eq(MemberCourseReservation::getMemberId, memberId)
                        .eq(MemberCourseReservation::getCourseId, courseId)
        ) != null) {
            // 如果存在记录，检查是否是已取消状态（status=2）
            MemberCourseReservation existingReservation = reservationMapper.selectOne(
                    new LambdaQueryWrapper<MemberCourseReservation>()
                            .eq(MemberCourseReservation::getMemberId, memberId)
                            .eq(MemberCourseReservation::getCourseId, courseId)
                            .eq(MemberCourseReservation::getStatus, 2)
            );

            // 如果是已取消状态，则更新该记录而不是插入新记录
            if (existingReservation != null) {
                existingReservation.setStatus(status != null ? status : 0);
                existingReservation.setCourseType(courseType);
                return reservationMapper.updateById(existingReservation) == 1;
            }

            return false; // 已存在且不是取消状态
        }

        MemberCourseReservation reservation = new MemberCourseReservation(memberId, courseId, status, courseType);
        return reservationMapper.insert(reservation) == 1;
    }

//取消预约根据预约ID
    @Override
    @Transactional
    @CacheEvict(value = "com.situ.crm2026.impl.courseServiceImpl", allEntries = true)
    public boolean cancel(Integer reservationId) {
        MemberCourseReservation reservation = reservationMapper.selectById(reservationId);
        if (reservation == null || reservation.getStatus() == 2) {
            return false;
        }
        reservation.setStatus(2);
        return reservationMapper.updateById(reservation) == 1;
    }

    @Override
    @Transactional
    public boolean confirm(Integer reservationId) {
        MemberCourseReservation reservation = reservationMapper.selectById(reservationId);
        if (reservation == null || reservation.getStatus() != 0) {
            return false;
        }
        reservation.setStatus(1);
        return reservationMapper.updateById(reservation) == 1;
    }

    //
    @Override
    public MemberCourseReservation findByMemberAndCourse(Integer memberId, Integer courseId) {
        return reservationMapper.selectOne(
                new LambdaQueryWrapper<MemberCourseReservation>()
                        .eq(MemberCourseReservation::getMemberId, memberId)
                        .eq(MemberCourseReservation::getCourseId, courseId)
        );
    }
    //检查课程时间是否冲突
    //在courseMapper里查出课程时间
    @Override
    public boolean hasTimeConflict(Integer memberId, Integer courseId) {
            //利用mybatis通过selectById获取课程对象这样就不用写sql
        Course newCourse=courseMapper.selectById(courseId);
        // 如果课程不存在，认为没有时间冲突（或根据业务需求返回true）
        if (newCourse == null) {
            return false;
        }
        //获取开课时间
        LocalDateTime newStart = newCourse.getStartTime();
        //获取课程时长
        int duration = Integer.parseInt(newCourse.getDuration());
        //得到课程的结束时间
        LocalDateTime newEnd = newStart.plusMinutes(duration);

        //冲突公式:  A_start < B_end && A_end > B_start

        List<Course> reservedCourses = courseMapper.selectMemberReservedTimeWithTime(memberId);
        for (Course reserved : reservedCourses) {
            int oldDuration = Integer.parseInt(reserved.getDuration());
            LocalDateTime oldStart = reserved.getStartTime();
            LocalDateTime oldEnd = oldStart.plusMinutes(oldDuration);

            // ️ 核心判断：是否有时间重叠
            boolean isOverlapping = newStart.isBefore(oldEnd) && newEnd.isAfter(oldStart);

            if (isOverlapping) {
                return true; // 有冲突
            }

        }
        return false; // 所有课程都不冲突
    }

    @Override
    public Page<ReservationDto> findAllWithDetails(Page<ReservationDto> page) {
        return reservationMapper.findAllWithDetails(page);
    }

    @Autowired
    public void setCourseMapper(CourseMapper courseMapper) {
        this.courseMapper = courseMapper;
    }
}
